<script setup lang="ts">
import type { MenuForm } from "@/types/Menu";
import { useI18n } from "vue-i18n";
import api from "@/plugins/http";
import type { ResponseResult } from "@/types/Response";

const { t } = useI18n();

const props = defineProps<{
  dialog: boolean;
  menuItem: any;
  Items: any;
}>();

const menuAll = computed(() => {
  let root = { id: "0", menuName: "Root" };
  return [root, ...props.Items];
});

const emit = defineEmits(["closeDialog"]);

const form = ref<MenuForm>({
  MenuName: "",
  IconName: "",
  RouteName: "",
  MenuType: 1, // 默认值
  ParentId: "0", // 默认 Root
  Sort: 0,
  IsHidden: false,
  ComponentPath: "", // 添加 ComponentPath
});
const formRef = ref();

const rules = {
  required: (value: any) => {
    // 检查 value 是否是 null 或 undefined
    if (value === null || value === undefined) {
      return t("Required");
    }
    // 检查是否是空字符串 (trim() 去除首尾空白)
    if (typeof value === "string" && value.trim() === "") {
      return t("Required");
    }
    // 如果是数字 0，则认为是有效值
    if (typeof value === "number" && value === 0) {
      return true;
    }
    // 对于其他非假值（如非空字符串、非0数字、true等），则通过
    return true;
  },
  number: (value: any) => !isNaN(parseFloat(value)) || t("MustBeNumber"),
};

const closeDialog = () => {
  emit("closeDialog");
};

const menuType = [
  { Name: "Group", Value: 0 },
  { Name: "Item", Value: 1 },
];
const menuHidden = [
  { Name: "YES", Value: true },
  { Name: "NO", Value: false },
];

const saveMenu = async () => {
  const { valid } = await formRef.value.validate();
  if (valid) {
    api.post("/api/MenuManager/AddMenuItem", form.value, "", (res: ResponseResult) => {
      ElMessage({
        message: t("OperateSuccessfully"),
        type: res.success ? "success" : "error",
      });
      if (res.success) {
        emit("closeDialog");
      }
    });
  }
};

onMounted(() => {
  if (props.menuItem) {
    form.value.ComponentPath = props.menuItem.componentPath;
    form.value.MenuName = props.menuItem.menuName;
    form.value.IconName = props.menuItem.iconName;
    form.value.RouteName = props.menuItem.routeName;
    form.value.MenuType = props.menuItem.type;
    form.value.ParentId = props.menuItem.parentId;
    form.value.Sort = props.menuItem.sort;
    form.value.IsHidden = props.menuItem.isHidden;
  }
});
</script>

<template>
  <v-dialog :model-value="dialog" @update:model-value="closeDialog" max-width="600px">
    <v-card>
      <v-card-title>
        <span class="text-h10">{{ menuItem == null ? t("Add") : t("Edit") }}</span>
      </v-card-title>

      <v-card-text>
        <v-container>
          <v-form fast-fail ref="formRef">
            <v-row>
              <v-col md="6">
                <v-select
                  prepend-inner-icon="mdi-account-details"
                  :items="menuAll"
                  :rules="[rules.required]"
                  item-title="menuName"
                  item-value="id"
                  :label="$t('Parent')"
                  variant="outlined"
                  clearable
                  density="compact"
                  v-model="form.ParentId"
                />
              </v-col>
              <v-col md="6">
                <v-select
                  prepend-inner-icon="mdi-form-select"
                  :items="menuType"
                  item-title="Name"
                  item-value="Value"
                  :label="$t('MenuType')"
                  variant="outlined"
                  density="compact"
                  v-model="form.MenuType"
                />
              </v-col>
              <v-col md="4">
                <v-text-field
                  prepend-inner-icon="mdi-text-box-edit"
                  :label="t('MenuName')"
                  :rules="[rules.required]"
                  variant="outlined"
                  density="compact"
                  v-model="form.MenuName"
                />
              </v-col>
              <v-col md="4">
                <v-text-field
                  prepend-inner-icon="mdi-emoticon-excited"
                  v-model="form.IconName"
                  :label="t('IconName')"
                  variant="outlined"
                  density="compact"
                ></v-text-field>
              </v-col>
              <v-col md="4">
                <v-text-field
                  prepend-inner-icon="mdi-router-network"
                  v-model="form.RouteName"
                  :label="t('RouteName')"
                  variant="outlined"
                  density="compact"
                ></v-text-field>
              </v-col>
              <v-col md="12">
                <v-text-field
                  prepend-inner-icon="mdi-file-code"
                  v-model="form.ComponentPath"
                  :label="t('ComponentPath')"
                  variant="outlined"
                  density="compact"
                ></v-text-field>
              </v-col>

              <v-col md="6">
                <v-number-input
                  prepend-inner-icon="mdi-sort-numeric-ascending"
                  :label="t('Sort')"
                  density="compact"
                  :rules="[rules.required, rules.number]"
                  v-model.number="form.Sort"
                  variant="outlined"
                  :min="0"
                />
              </v-col>
              <v-col md="6">
                <v-select
                  prepend-inner-icon="mdi-eye"
                  :items="menuHidden"
                  item-title="Name"
                  item-value="Value"
                  :label="$t('IsHidden')"
                  variant="outlined"
                  density="compact"
                  v-model="form.IsHidden"
                />
              </v-col>
            </v-row>
          </v-form>
        </v-container>
      </v-card-text>

      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn color="blue-darken-1" variant="text" @click="closeDialog">
          {{ t("Cancel") }}
        </v-btn>
        <v-btn color="blue-darken-1" variant="text" @click="saveMenu">
          {{ t("Save") }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped></style>
